<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Demo</title>
    <style>
        #output {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            min-height: 100px;
            max-width: 500px;
            white-space: pre-wrap;
        }
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <h1>Server-Sent Events Demo</h1>
    <button id="startBtn">Start Stream</button>
    <div id="output">Waiting for data...</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const startBtn = document.getElementById('startBtn');
            const output = document.getElementById('output');
            let eventSource = null;

            startBtn.addEventListener('click', function() {
                // Clear previous output
                output.textContent = '';
                
                // Disable button during streaming
                startBtn.disabled = true;
                
                // Create a new EventSource connection
                eventSource = new EventSource('http://localhost:8081/sse/time');
                
                eventSource.addEventListener('time-update', function(event) {
                    // Append new data to output
                    output.textContent += event.data + '\n';
                    
                    // Scroll to bottom
                    output.scrollTop = output.scrollHeight;
                });
                
                eventSource.addEventListener('complete', function(event) {
                    // Append completion message
                    output.textContent += event.data + '\n';
                    
                    // Close the connection
                    eventSource.close();
                    startBtn.disabled = false;
                });
                
                eventSource.onerror = function() {
                    // Close the connection when error occurs
                    output.textContent += 'Error occurred or connection closed\n';
                    if (eventSource) {
                        eventSource.close();
                    }
                    startBtn.disabled = false;
                };
            });
        });
    </script>
</body>
</html>